﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using NetDon.OA.Portal.HtmlTool;
using NetDon.eBoss.Data;
using NetDon.eBoss.Data.CollectionClasses;
using NetDon.eBoss.Data.EntityClasses;
using NetDon.eBoss.Data.HelperClasses;
using NetDon.eBoss.Data.Linq;
using NetDon.eBoss.Data.RelationClasses;
using NetDon.eBoss.Portal.Common;
using SD.LLBLGen.Pro.ORMSupportClasses;

namespace NetDon.eBoss.Portal.HtmlTool
{
    public class HtmlToolService
    {
        #region template edit
        public ProductgroupEntity GetProductGroupByItemNoAndColor(string itemNo, string color, int accountId)
        {

            var metaData = new LinqMetaData();
            var issuingOrder = metaData.Productgroup.FirstOrDefault(order => order.Itemno == itemNo && order.Color == color && order.Accountid ==accountId);
            return issuingOrder;
        }

        public ProductgroupCollection GetProductGroupByAccountId(int accountId)
        {

            var customerInfoCollection = new ProductgroupCollection();
            customerInfoCollection.GetMulti(ProductgroupFields.Accountid == accountId);
            return customerInfoCollection;
        }

        public ProductgroupEntity GetProductGroupByAccountIdAndSourceId(int accountId, int sourceId)
        {

            var customerInfoCollection = new ProductgroupCollection();
            customerInfoCollection.GetMulti(ProductgroupFields.Accountid == accountId & ProductgroupFields.Sourceid == sourceId);
            return customerInfoCollection.FirstOrDefault();
        }

        public bool RemoveProductGroups(int customerId)
        {
            var customerInfoCollection = new ProductgroupCollection();
            var result = customerInfoCollection.DeleteMulti(ProductgroupFields.Sourceid == customerId);

            return result > 0;
        }
        public bool RemoveTemplates(IEnumerable<int> ids)
        {
            var trans = new Transaction(IsolationLevel.ReadCommitted, "RemoveTemplates");
            try
            {
                foreach (var id in ids)
                {
                    var customerInfoCollection = new ProductgroupCollection();
                    trans.Add(customerInfoCollection);
                    customerInfoCollection.DeleteMulti(ProductgroupFields.Sourceid == id);
                }
                trans.Commit();

            }
            catch (Exception)
            {
                trans.Rollback();

                throw;
            }
            return true;

        }
        public int GetCustomerInfoCount(HtmlToolCriteria criteria)
        {
            var collection = new ProductgroupCollection();
            return int.Parse(collection.GetScalar(ProductgroupFieldIndex.Id, null, AggregateFunction.CountDistinct, GetSearchCustomerInfoPredicate(criteria), GetOrderSearchRelations(), null).ToString());
        }

        public ProductgroupCollection SearchCustomerInfoDatasByCondition(HtmlToolCriteria criteria, string sortExpression, System.Web.UI.WebControls.SortDirection sortDirection, int pageSize, int pageIndex)
        {
            var sort = GetSortExpression(sortExpression, sortDirection);
            var collection = new ProductgroupCollection();
            collection.GetMulti(GetSearchCustomerInfoPredicate(criteria), 0, sort,
                              GetOrderSearchRelations(), pageIndex + 1, pageSize);




            return collection;
        }


        private IRelationCollection GetOrderSearchRelations()
        {
            var relation = new RelationCollection(ProductgroupEntity.Relations.HtmltooltrademarksettingEntityUsingTrademarkid, JoinHint.Left);
            relation.Add(ProductgroupEntity.Relations.HtmltoolstyleEntityUsingStyleid, JoinHint.Left);

            return relation;
        }


        public ProductgroupEntity Clone(ProductgroupEntity entity, int accountId)
        {
            var cloned = new ProductgroupEntity();
            cloned.Accountid = accountId;
            cloned.Sourceid = entity.Id;

            cloned.Productcode = entity.Productcode;
            cloned.Itemno = entity.Itemno;
            cloned.Color = entity.Color;
            cloned.Productname = entity.Productname;
            cloned.Description = entity.Description;
            cloned.Comment = entity.Comment;
            cloned.Material = entity.Material;
            cloned.Size = entity.Size;
            cloned.Retailprice = entity.Retailprice;
            cloned.Specifics = entity.Specifics;
            cloned.Market = entity.Market;
            cloned.Brand = entity.Brand;
            cloned.Picurl1 = entity.Picurl1;
            cloned.Picurl2 = entity.Picurl2;
            cloned.Picurl3 = entity.Picurl3;
            cloned.Picurl4 = entity.Picurl4;
            cloned.Picurl5 = entity.Picurl5;
            cloned.Picurl6 = entity.Picurl6;
            cloned.Picurl7 = entity.Picurl7;
            cloned.Picurl8 = entity.Picurl8;
            cloned.Picurl9 = entity.Picurl9;
            cloned.Picurl10 = entity.Picurl10;
            cloned.Picurl11 = entity.Picurl11;
            cloned.Picurl12 = entity.Picurl12;
            cloned.Sizetable = entity.Sizetable;
            cloned.Englishtitle = entity.Englishtitle;
            cloned.Quantity = entity.Quantity;
            cloned.Templateid = entity.Templateid;
            cloned.Tag = entity.Tag;
            cloned.Categoryruleid = entity.Categoryruleid;
            cloned.Trademarkid = entity.Trademarkid;
            cloned.Styleid = entity.Styleid;
            cloned.Colorid = entity.Colorid;

            return cloned;
        }
        private SortExpression GetSortExpression(string strInput, SortDirection sortDirection)
        {
            SortExpression sort;
            switch (strInput)
            {
                case "Tag":
                    sort = new SortExpression(ProductgroupFields.Tag | (SortOperator)(int)sortDirection);
                    break;
                case "Productcode":
                    sort = new SortExpression(ProductgroupFields.Productcode | (SortOperator)(int)sortDirection);
                    break;
                case "Color":
                    sort = new SortExpression(ProductgroupFields.Color | (SortOperator)(int)sortDirection);
                    break;

                case "Productname":
                    sort = new SortExpression(ProductgroupFields.Productname | (SortOperator)(int)sortDirection);
                    break;
                case "Itemno":
                    sort = new SortExpression(ProductgroupFields.Itemno | (SortOperator)(int)sortDirection);
                    break;
                case "Englishtitle":
                    sort = new SortExpression(ProductgroupFields.Englishtitle | (SortOperator)(int)sortDirection);
                    break;
                default:
                    sort = new SortExpression
                               {
                                   ProductgroupFields.Productcode | SortOperator.Ascending
                               };
                    sort.Add(new SortClause(ProductgroupFields.Color, SortOperator.Ascending));
                    break;

            }
            return sort;
        }

        private IPredicate GetSearchCustomerInfoPredicate(HtmlToolCriteria criteria)
        {
            var expression = new PredicateExpression();
            if (criteria.Tag.HasValue)
            {
                expression.Add(ProductgroupFields.Tag == criteria.Tag.Value);
            }
            if (criteria.CategoryRuleId.HasValue)
            {
                expression.Add(ProductgroupFields.Categoryruleid == criteria.CategoryRuleId.Value);
            }

            if (!string.IsNullOrEmpty(criteria.Color))
            {
                expression.Add(ProductgroupFields.Color % ("%" + criteria.Color + "%"));
            }
            if (!string.IsNullOrEmpty(criteria.ItemNo))
            {
                expression.Add(ProductgroupFields.Itemno % ("%" + criteria.ItemNo + "%"));
            }
            if (!string.IsNullOrEmpty(criteria.ProductName))
            {
                expression.Add(ProductgroupFields.Productname % ("%" + criteria.ProductName + "%"));
            }

            if (!string.IsNullOrEmpty(criteria.Style))
            {
                expression.Add(HtmltoolstyleFields.Style % ("%" + criteria.Style + "%"));
            }
            if (!string.IsNullOrEmpty(criteria.Trademark))
            {
                expression.Add(HtmltooltrademarksettingFields.Name % ("%" + criteria.Trademark + "%"));
            }
            expression.Add(ProductgroupFields.Id == ProductgroupFields.Sourceid); //for default account id
            return expression;
        }


        #endregion

        #region Trademark
        public int GetTrademarkCount(TrademarkCriteria criteria)
        {
            var collection = new HtmltooltrademarksettingCollection();
            return int.Parse(collection.GetScalar(HtmltooltrademarksettingFieldIndex.Id, null, AggregateFunction.CountDistinct, GetSearchTrademarkPredicate(criteria)).ToString());
        }

        private IPredicate GetSearchTrademarkPredicate(TrademarkCriteria criteria)
        {
            var expression = new PredicateExpression();
            if (!string.IsNullOrEmpty(criteria.Name))
            {
                expression.Add(HtmltooltrademarksettingFields.Name % ("%" + criteria.Name + "%"));
            }

            return expression;
        }
        public HtmltooltrademarksettingCollection SearchTrademarkByCondition(TrademarkCriteria criteria, string sortExpression, System.Web.UI.WebControls.SortDirection sortDirection, int pageSize, int pageIndex)
        {
            var sort = GetTrademarkSortExpression(sortExpression, sortDirection);
            var collection = new HtmltooltrademarksettingCollection();
            collection.GetMulti(GetSearchTrademarkPredicate(criteria), 0, sort,
                              null, pageIndex + 1, pageSize);




            return collection;
        }
        private SortExpression GetTrademarkSortExpression(string strInput, SortDirection sortDirection)
        {
            SortExpression sort;
            switch (strInput)
            {
                case "Name":
                    sort = new SortExpression(HtmltooltrademarksettingFields.Name | (SortOperator)(int)sortDirection);
                    break;
                case "Market":
                    sort = new SortExpression(HtmltooltrademarksettingFields.Market | (SortOperator)(int)sortDirection);
                    break;

                default:
                    sort = new SortExpression
                               {
                                   HtmltooltrademarksettingFields.Name | SortOperator.Ascending
                               };
                    sort.Add(new SortClause(HtmltooltrademarksettingFields.Name, SortOperator.Ascending));
                    break;

            }
            return sort;
        }
        #endregion


        public BrandsettingEntity GetBrandSetting(int siteCode)
        {
            var collection = new BrandsettingCollection();
            collection.GetMulti(BrandsettingFields.Sitecode ==siteCode);
            return collection.FirstOrDefault();
        }

        public TitlesettingEntity GetTitleColorSetting(string color)
        {
            var brandSettingCollection = new TitlesettingCollection();
            brandSettingCollection.GetMulti(TitlesettingFields.Color == color);
            return brandSettingCollection.FirstOrDefault();
        }

        public SizesettingEntity GetSizeSetting(string size, int site)
        {
            var sizesettingCollection = new SizesettingCollection();
            sizesettingCollection.GetMulti(SizesettingFields.Size == size & SizesettingFields.Sitecode == site);
            return sizesettingCollection.FirstOrDefault();
        }

        public void InsertTitleColorSetting(string color)
        {
            if (GetTitleColorSetting(color) == null)
            {
                var setting = new TitlesettingEntity();
                setting.Color = color;
                setting.Save();

            }
        }

        public void InsertSizeSetting(string size)
        {
            if (GetSizeSetting(size, (int)eBaySites.US) == null)
            {
                var setting = new SizesettingEntity();
                setting.Size = size;
                setting.Batchid = Guid.NewGuid().ToString();
                setting.Sitecode = (int)eBaySites.US;
                setting.Save();

            }
        }


        public IEnumerable<SiteValues> GetStyleSettings(string categoryRuleId)
        {
            var styles = new HtmltoolstyleCollection();
            styles.GetMulti(HtmltoolstyleFields.Categoryruleid == categoryRuleId);
            var siteValues = new List<SiteValues>();
            var stylesGroupByBatchId = styles.GroupBy(s => s.Batchid);
            foreach (var style in stylesGroupByBatchId)
            {
                var siteValue = new SiteValues();
                foreach (var styleSetting in style)
                {
                    siteValue.Id = categoryRuleId;
                    siteValue.SetCurrentValue(styleSetting.Sitecode, styleSetting.Style, styleSetting.Batchid);
                }
                siteValues.Add(siteValue);
            }
            return siteValues;
        }

        public IEnumerable<SiteValues> GetColorSettings()
        {
            var styles = new HtmltoolcolorCollection();
            styles.GetMulti(null);
            var siteValues = new List<SiteValues>();
            var stylesGroupByBatchId = styles.GroupBy(s => s.Batchid);
            foreach (var style in stylesGroupByBatchId)
            {
                var siteValue = new SiteValues();
                foreach (var styleSetting in style)
                {
                    siteValue.SetCurrentValue(styleSetting.Sitecode, styleSetting.Color, styleSetting.Batchid);
                }
                siteValues.Add(siteValue);
            }
            return siteValues;
        }


        public HtmltoolcategoryruleEntity GetHtmltoolCategoryBySize(string size)
        {
            var metaData = new LinqMetaData();
            var issuingOrder = metaData.Htmltoolcategoryrule.ToList().FirstOrDefault(order => size.Contains(order.Rule));
            return issuingOrder;

        }

        public string GetHtmltoolCategoryById(int? categoryRuleId)
        {
            if (!categoryRuleId.HasValue) return string.Empty;
            return new HtmltoolcategoryruleEntity(categoryRuleId.Value).Ebaycategory;

        }
        public HtmltoolcolorEntity GeteBayColorByBatchIdAndSiteCode(string batchId, int siteCode)
        {
            var collections = new HtmltoolcolorCollection();
            collections.GetMulti(HtmltoolcolorFields.Batchid == batchId & HtmltoolcolorFields.Sitecode == siteCode);
            return collections.FirstOrDefault();
        }

        public HtmltoolstyleEntity GeteBaystyleByBatchIdAndSiteCode(string batchId, int siteCode)
        {
            var collections = new HtmltoolstyleCollection();
            collections.GetMulti(HtmltoolstyleFields.Batchid == batchId & HtmltoolstyleFields.Sitecode == siteCode);
            return collections.FirstOrDefault();
        }

        public string GeteBayColorByColor(string color, int siteCode)
        {
            var ebayColor = string.Empty;
            var titleSetting = GetTitleColorSetting(color);
            if (titleSetting !=null && titleSetting.Htmltoolcolorid.HasValue)
            {
                var htmlToolColor = GeteBayColorByBatchIdAndSiteCode(titleSetting.Htmltoolcolor.Batchid, siteCode);
                ebayColor = htmlToolColor.Color;
            }

            return ebayColor;
        }

        public string GetTradeMarkById(int? tradeMarkId)
        {
            var tradeMark = string.Empty;
            if (tradeMarkId.HasValue)
            {
                tradeMark = new HtmltooltrademarksettingEntity(tradeMarkId.Value).Name;

            }

            return tradeMark;
        }

        public string GeteBayStyleById(int? styleId, int siteCode)
        {
            var ebayStyle = string.Empty;

            if (styleId.HasValue)
            {
                var htmlToolColor = GeteBaystyleByBatchIdAndSiteCode(new HtmltoolstyleEntity(styleId.Value).Batchid, siteCode);
                ebayStyle = htmlToolColor.Style;
            }

            return ebayStyle;
        }

        public void CloneAccounts(int sourceAccount, int accountId)
        {  
            var productGroups = this.GetProductGroupByAccountId(sourceAccount);
            foreach (var productGroup in productGroups)
            {

                CloneProductByAccountId(accountId, productGroup);
            }
        }
        private void CloneProductByAccountId(int accountId, ProductgroupEntity productGroup)
        {
            //check if exists
            if (this.GetProductGroupByAccountIdAndSourceId(accountId, productGroup.Id) == null)
            {
                var cloned = this.Clone(productGroup, accountId);
                cloned.Save();
            }
        }
        internal void CloneAllOtherAccounts(ProductgroupEntity existingProductGroupEntity)
        {
            var allAccounts = new HtmlToolAccountService().GetHtmlToolAccounts();
            foreach(var account in allAccounts)
            {
                if (account.Id == existingProductGroupEntity.Accountid) continue;
                CloneProductByAccountId(account.Id, existingProductGroupEntity);
            }
        }
    }

    [Serializable]
    public class HtmlToolCriteria
    {
        public int? Tag { get; set; }
        public string ItemNo { get; set; }
        public string Color { get; set; }
        public string ProductName { get; set; }
        public string Trademark { get; set; }
        public string Style { get; set; }
        public int? CategoryRuleId { get; set; }
    }

    [Serializable]
    public class TrademarkCriteria
    {
        public string Name { get; set; }
    }


    [Serializable]
    public class SiteValues
    {
        public string Id { get; set; }
        public string BatchId { get; set; }
        public string USValue { get; set; }
        public string AUValue { get; set; }
        public string UKValue { get; set; }
        public string DEValue { get; set; }
        public string FRValue { get; set; }
        public string ITValue { get; set; }

        public string Site1Value { get; set; }
        public string Site2Value { get; set; }
        public string Site3Value { get; set; }
        public string Site4Value { get; set; }

        public void SetCurrentValue(int? currentSite, string value, string batchId)
        {
            BatchId = batchId;
            var site = (eBaySites)Enum.Parse(typeof(eBaySites), (currentSite ?? 0).ToString());
            if (site == eBaySites.US)
            {
                this.USValue = value;
            }

            if (site == eBaySites.UK)
            {
                this.UKValue = value;
            }

            if (site == eBaySites.AU)
            {
                this.AUValue = value;
            }

            if (site == eBaySites.DE)
            {
                this.DEValue = value;
            }
            if (site == eBaySites.FR)
            {
                this.FRValue = value;
            }
            if (site == eBaySites.IT)
            {
                this.ITValue = value;
            }
            if (site == eBaySites.Site1)
            {
                this.Site1Value = value;
            }
            if (site == eBaySites.Site2)
            {
                this.Site2Value = value;
            }
            if (site == eBaySites.Site3)
            {
                this.Site3Value = value;
            }
            if (site == eBaySites.Site4)
            {
                this.Site4Value = value;
            }

        }

    }



}
